package Servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "uploads";
    private static final String ABSOLUTE_UPLOAD_PATH = "D:\\desktop\\bill-system-master\\src\\main\\webapp\\" + UPLOAD_DIR;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File uploadDir = new File(ABSOLUTE_UPLOAD_PATH);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        Collection<Part> parts = request.getParts();
        boolean uploadSuccess = false;
        String fileUrl = ""; // 用于存储文件的访问 URL


        for (Part part : parts) {
            String fileName = part.getSubmittedFileName();
            if (fileName != null && !fileName.isEmpty()) {
                String uniqueFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                part.write(ABSOLUTE_UPLOAD_PATH + File.separator + uniqueFileName);
                uploadSuccess = true;
                // 构造文件的访问 URL
                fileUrl = request.getContextPath() + "/" + UPLOAD_DIR + "/" + uniqueFileName;
                break; // 只处理第一个文件
            }
        }

        response.setContentType("application/json");
        if (uploadSuccess) {
            response.getWriter().print("{\"success\": true, \"url\": \"" + fileUrl + "\"}");
        } else {
            response.getWriter().print("{\"success\": false, \"message\": \"No file uploaded.\"}");
        }
    }
}